package com.gitee.cui.basic.use;

import com.gitee.cui.util.ThreadUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 线程中的守护线程演示
 * @author cuiqingqiang
 * @version 1.0
 * @date 2021/11/10 15:52
 **/
@Slf4j
public class Daemon {

    private static final int SLEEP_GAP = 5000;

    private static final int TURN = 5;

    static class DaemonThread extends Thread {
        public DaemonThread() {
            super("daemonThread");
        }

        @Override
        public void run() {
            log.info("--daemon线程开始");
            int i = 1;
            while (true) {
                log.info("--轮次：" + i + "--守护状态为：{}", isDaemon());
                i++;
                ThreadUtil.sleepMilliSeconds(SLEEP_GAP);
            }
        }
    }

    public static void main(String[] args) {
        DaemonThread daemonThread = new DaemonThread();
        daemonThread.setDaemon(true);
        daemonThread.start();

        Thread userThread = new Thread(() ->{
           log.info(">>用户线程开始");
            for (int i = 1; i < TURN; i++) {
                log.info(">>轮次：" + i + ">>守护状态为：{}", ThreadUtil.getCurThread().isDaemon());
                ThreadUtil.sleepMilliSeconds(SLEEP_GAP);
            }
            log.info(">>用户线程结束");
        }, "userThread");
        userThread.start();
        log.info(" 守护状态为：{}", ThreadUtil.getCurThread().isDaemon());
        log.info("{} 运行结束", ThreadUtil.getCurThreadName());

    }
}
